package cn.car91.activity;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import cn.car91.R;
import cn.car91.adapter.ExposureListAdapter;
import cn.car91.bean.Exposure;
import cn.car91.bean.User;
import cn.car91.pager.ExposurePager;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.view.FooterView.Item;
import cn.car91.view.XListView;
import cn.car91.view.XListView.IXListViewListener;
import cn.car91.view.XListViewFooter;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

public class ExposureMainActivity extends BaseActivity {
    private final int Request_Code = 22001;

    private ExposurePager exposurePager = new ExposurePager();

    @ViewInject(R.id.exposure_list)
    XListView exposureList;
    @ViewInject(R.id.none)
    View none;

    ExposureListAdapter exposureListAdapter;

    boolean addDate = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_exposure_main);
        super.onCreate(savedInstanceState);

        exposureListAdapter = new ExposureListAdapter(this, R.layout.view_exposure_item);
        exposureList.setAdapter(exposureListAdapter);

        exposureList.setOnItemClickListener(onExposureItemClickListener);

        exposureList.setPullLoadEnable(true);
        exposureList.setPullRefreshEnable(true);
        exposureList.setXListViewListener(onExposureViewListener);

        registerReceiver(itemChangeBroadcastReceiver, new IntentFilter(MainFragmentActivity.naviAction));
   
        ((TextView) findViewById(R.id.header_text)).setText("诚信曝光");
    }

    private IXListViewListener onExposureViewListener = new IXListViewListener() {
        @Override
        public void onRefresh() {
            addDate = false;
            exposurePager.reset();
            exposureList.getmFooterView().setState(XListViewFooter.STATE_NORMAL);
            getData();
        }

        @Override
        public void onLoadMore() {
            addDate = true;
            getData();
        }
    };

    /**
     * 停止刷新，
     */
    private void onStopLoad() {
        exposureList.stopRefresh();
        exposureList.stopLoadMore();
        exposureList.setRefreshTime("刚刚");
    }

    private void getData() {
    	/*String key = SearchActivity.searchKey;
        if (RegexUtil.isNull(key)) {*/
        	exposurePager.getPublicData(callBackExposures);
        /*} else {
        	exposurePager.getSearchData(key, callBackExposures);
        }*/
    }

    @OnClick(R.id.exposure_push_btn)
    public void onPushClick(View v) {
        User user = getCar91Application().getUser();
        if (user != null) {
            Intent intent = new Intent();
            intent.setClass(ExposureMainActivity.this, ExposurePushActivity.class);
            startActivity(intent);
        } else {
        	Intent intent = new Intent();
            intent.setClass(ExposureMainActivity.this, UserLoginActivity.class);
            startActivityForResult(intent, Request_Code);
            /*new MyAlertDialog.Builder(ExposureMainActivity.this)
                    .setMessage("请先登录")
                    .setPositiveButton("登录", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            // TODO Auto-generated method stub
                            Intent intent = new Intent();
                            intent.setClass(ExposureMainActivity.this, UserLoginActivity.class);
                            startActivityForResult(intent, Request_Code);
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create().show();*/
        }
    }

    private OnItemClickListener onExposureItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
            //TextView idView = (TextView) arg1.findViewById(R.id.exposure_item_id);
            String eid = String.valueOf(exposureListAdapter.getExposureId(arg2-1));//arg2起始为1

            Intent intent = new Intent();
            intent.putExtra("eid", eid);
            intent.setClass(ExposureMainActivity.this, ExposureDetailActivity.class);
            startActivity(intent);
        }
    };

    private void showTextWhenNone(Boolean show) {
        if (show) {
            if (exposureList.getVisibility() == View.VISIBLE) {
                exposureList.setVisibility(View.GONE);
            }
            if (none.getVisibility() == View.GONE) {
                none.setVisibility(View.VISIBLE);
            }
        } else {
            if (exposureList.getVisibility() == View.GONE) {
                exposureList.setVisibility(View.VISIBLE);
            }
            if (none.getVisibility() == View.VISIBLE) {
                none.setVisibility(View.GONE);
            }
        }
    }

    private RequestCallBack callBackExposures = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            // TODO Auto-generated method stub
            onStopLoad();
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            List<Exposure> exposures = Car91JsonUtil.getDTOList(arg0.result.toString(), Exposure.class);
            onStopLoad();
            if (exposures.size() > 0) {
                showTextWhenNone(false);
                if (addDate) {
                    exposureListAdapter.addData(exposures);
                } else {
                    exposureListAdapter.setData(exposures);
                }
                exposureListAdapter.notifyDataSetChanged();
                addDate = true;
            } else if (!addDate) {
                showTextWhenNone(true);
            } else {
                exposureList.getmFooterView().getmHintView().setText(getResources().getString(R.string.xlistview_footer_hint_nomore));
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == Request_Code) {
            switch (resultCode) {
                case Car91ResultCode.Refresh_User_Code:
                    Intent intent = new Intent();
                    intent.setClass(ExposureMainActivity.this, ExposurePushActivity.class);
                    startActivity(intent);
                    break;

                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private BroadcastReceiver itemChangeBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            int item = arg1.getIntExtra("curItem", Item.CB_INDEX_repairshop);
            //hiddenPopuWindow();

            if (item == Item.CB_INDEX_exposure) {
                exposurePager.reset();
                addDate = false;
                getData();
            } else {
                /*String searchItem = SearchActivity.item;
                if (searchItem!=null&&searchItem.equals("exposure")) {
                    SearchActivity.clearSearchInfo();
                }*/
            }
        }
    };

    @Override
    protected void onDestroy() {
        unregisterReceiver(itemChangeBroadcastReceiver);
        super.onDestroy();
    }
}
